package com.cg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cg.dto.StartQuizDTO;
import com.cg.entity.Question;
import com.cg.entity.Quiz;
import com.cg.mapper.QuizMapper;
import com.cg.result.R;
import com.cg.service.AccountService;
import com.cg.service.IQuestionService;
import com.cg.service.IQuizService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 加
 * @since 2025-01-17
 */
@Service
public class QuizServiceImpl extends ServiceImpl<QuizMapper, Quiz> implements IQuizService {

    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IQuizService quizService;
    @Autowired
    private AccountService accountService;
    @Override
    public R startQuiz(StartQuizDTO startQuizDTO) {
        System.out.println("1" + startQuizDTO.getQuestionId());
        System.out.println("2" + quizService.selectQuizByQuestionId(startQuizDTO.getQuestionId()));
        Quiz quiz = new Quiz();
        BeanUtils.copyProperties(startQuizDTO, quiz);
        quiz.setUserId(accountService.getCurrentUserId());
        Question question = questionService.selectQuestionById2(startQuizDTO.getQuestionId());
        if(question==null){
            return R.Failed("不存在该题目");
        }
        if (quiz.getCAnswer().equals(question.getRAnswer())) {
            quiz.setIsCorrect(true);
        } else {
            quiz.setIsCorrect(false);
        }
            save(quiz);
            return R.Success(quiz);
    }

    @Override
    public String selectQuizByQuestionId(Long questionId) {
        LambdaQueryWrapper<Quiz> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Quiz::getQuestionId,questionId);

        List<Quiz> quizList=new ArrayList<>();
        quizList=list(queryWrapper);
        String list=quizList.toString();
        if((list!=null)&&(!list.isEmpty())) {
            return list;
        }
        else{
            return null;
        }
    }


    @Override
    public Long selectQuizIdByQuestionId(Long questionId) {
        LambdaQueryWrapper<Quiz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Quiz::getQuestionId, questionId);
        Quiz quiz = quizService.getOne(queryWrapper);
        if(quiz!=null) {
            return quiz.getQuizId();
        }else{
            return null;
        }
    }
}
